
import CCLog from "./CCLog";
import { JsbTileTrileTileCallMgr } from "./Common/JsbMgr";
import LanguagetileTile from "./Common/Language";
import { PROJECT_CONFIG } from "./Common/ProjectConfig";
import UITileToast from "./Common/UIToast";
import GameTileStaticData from "./GameStaticData";
import NetShowError from "./fxTs/NetError";
import { HttpLocalManager } from "./net/HttpLocalManager";

interface DeviceInfo {
    requestTime:number,
    country:string,
    chour:number,
    requestId:string,
    displayCountry:string,
    timeZone:string,
    appCode:string,
    secret:string,
    userId:string,
}



export class HttpTileCrushServerMgr{
    static isLocal=true;//true: 表示用本地数据
    static isTestUrl = false;
    static timeoutFlag=null;
    static netIsConnect=false;//是否已连接网络
    static timeout=20000;//请求超时
    static serverUrl=PROJECT_CONFIG.serverUrl;
    static testServerUrl=PROJECT_CONFIG.testServerUrl;
    static sendUrl = ""
    private static baseUrl: string = HttpTileCrushServerMgr.isTestUrl?HttpTileCrushServerMgr.testServerUrl:HttpTileCrushServerMgr.serverUrl;

    /**POST请求 */
    public static post(url:string, useLocal: boolean = false, params: object = {}):Promise<Response> {
        HttpTileCrushServerMgr.sendUrl = url
        if (HttpTileCrushServerMgr.isLocal && useLocal) {
            return new Promise((resolve, reject) => {
               
                HttpLocalManager.getResponseStr(url, function(responseStr: string) {
                    let responseObj:Response=JSON.parse(responseStr);
                    resolve(responseObj)
                });
                // let callBack = ()=>{
                //     HttpLocalManager.getResponseStr(url, function(responseStr: string) {
                //         let responseObj:Response=JSON.parse(responseStr);
                //         resolve(responseObj)
                //     });
                // }
                // GameStaticData.getNetErroScript().showNetError(callBack);
                
            })
        } else { 
            return new Promise(async (resolve, reject) => { 
                let defaultParam = this.getDefault()
                let msgPack = {
                    m:url,
                    commonInfo:defaultParam
                }
                Object.assign(msgPack,params)

                CCLog.log("HttpSend:", JSON.stringify(msgPack))
                let xhr = new XMLHttpRequest();
                xhr.open("POST", HttpTileCrushServerMgr.baseUrl, true);
                xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                xhr.setRequestHeader("appCode", defaultParam.appCode);
                let param =  JsbTileTrileTileCallMgr.handler("encodeMesPack","123",JSON.stringify(msgPack));
                CCLog.log(param)
                this.send(xhr,resolve,param); 
            })
        }
    }

    public static send(xhr: XMLHttpRequest,resolve:(value: any) => void,dataStr?:string){
        let timeoutFlag=null;
        if(cc.sys.os===cc.sys.OS_ANDROID){
            let isNetConnect = JsbTileTrileTileCallMgr.handler("isNetworkConnect","()Ljava/lang/String;")
            if (isNetConnect == "true") {
                HttpTileCrushServerMgr.netIsConnect = true;
            }else{
                HttpTileCrushServerMgr.netIsConnect = false;
            }
        }else{
            HttpTileCrushServerMgr.netIsConnect = false;
        }
        if(!HttpTileCrushServerMgr.netIsConnect){
            if (HttpTileCrushServerMgr.sendUrl!="J_V2_RP") {
                GameTileStaticData.getNetErroScript().showNetError(null);
            }
            
            resolve({
            resCode:-2,
            msg_desc:'',
            data:""
            })
            
            return;
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                clearTimeout(timeoutFlag);
                let response = xhr.responseText;
                if (xhr.status >= 200 && xhr.status < 300) {
                    let responseObj:Response=JSON.parse(response); 
                    try{
                        if(responseObj.resCode !== 0){
                            if ( ((responseObj.msg) + "").trim() != "" ){
                                UITileToast.popUp(responseObj.msg);
                            }
                            return;
                        }else if (responseObj.data){

                            responseObj.data =  JsbTileTrileTileCallMgr.handler("decodeMesPack","123",JSON.stringify(responseObj.data));

                            
                            responseObj.data = JSON.parse(responseObj.data)
                            // try {
                            //     if(cc.sys.os===cc.sys.OS_ANDROID){
                            //         responseObj.data = JSON.parse(responseObj.data)
                            //         console.log("REQ:",JSON.stringify(responseObj))
                            //     }else{
                            //         console.log("REQ:",responseObj.data)
                            //     }
                            // } catch (error) {
                            //     console.log("服务器解析抱错",error)
                            //     resolve(response)
                            // }
                        }
                        CCLog.log("结果",JSON.stringify(responseObj))
                        resolve(responseObj)
                    }catch{
                        resolve({
                            resCode:-3,
                            msg:'net data parsing failure',
                            data:""
                        })
                        return;
                    }
                } else {
                    let callBack = ()=>{
                        let defaultParam2 = HttpTileCrushServerMgr.getDefault()
                        let xhr1 = new XMLHttpRequest();
                        xhr1.open("POST", HttpTileCrushServerMgr.baseUrl, true);
                        xhr1.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
                        xhr1.setRequestHeader("appCode", defaultParam2.appCode);
    
                        HttpTileCrushServerMgr.send(xhr1,resolve,dataStr);
                    }
                    if (HttpTileCrushServerMgr.sendUrl!="J_V2_RP") {
                        GameTileStaticData.getNetErroScript().showNetError(callBack);
                    }
                    
                    // resolve({
                    //     resCode:-2,
                    //     msg:Language.getWord("NetFail"),
                    //     data:""
                    // })
                  

                }
            }
        };
        // console.log("dataStr=",dataStr)
        xhr.send(dataStr);

        timeoutFlag=setTimeout(()=>{//计时器，超时后处理
            clearTimeout(timeoutFlag);
            resolve({
                resCode:-1,
                msg: LanguagetileTile.getWord("NetReqTimeOut"),
                data:""
            })
            xhr.abort();
        },HttpTileCrushServerMgr.timeout);
    }

    static getDefault(){
        let time = new Date()
        if (CC_JSB){
            let CommonParam = JsbTileTrileTileCallMgr.handler("getCommonParm","()Ljava/lang/String;")
            return JSON.parse(CommonParam);
        }else{

          
            return {
                requestTime:time,
                country:"en",
                chour:time.getHours(),
                requestId:"3de12246-64d6-42cb-afc5-74c7cfb8ffff",
                displayCountry:"cn",
                timeZone:"GMT+08:00",
                appCode:"luckytiles",
                secret:"543BE8E71CBD38D99D959E96499A50A4",
                userId:"e9f3a3807ae2c584b1e52913de6e80b3",
            }
        }
    }
}

export interface Response{
    resCode:number
    msg:string
    data?:any
}